<template>

  <el-card shadow="never" class="border-0">
    <!-- 搜索 -->
    <SearchForm :model="searchForm" @search="getList" @reset="resetSearchForm">
      <SearchItem label="">

        <div class="mt-4" style="width: 100%;margin-left: 0px !important;">
          <el-input v-model="searchForm.name" placeholder="名称" class="input-with-select">
            <template #prepend>
              <el-button :icon="Search" />
            </template>
          </el-input>
        </div>


      </SearchItem>
    </SearchForm>

    <!-- 新增|刷新 -->
    <ListHeader layout="create,refresh" @create="handleCreate" @refresh="getList" />

    <el-table :data="tableData" stripe style="width: 100%; text-align: center" v-loading="loading" border>
      <el-table-column type="index" label="序号" width="100" style="text-align: center" align="center " />
      <el-table-column prop="name" label="部门名称" width="300" style="text-align: center" align="center " />
      <el-table-column prop="company_name" label="公司名称" style="text-align: center" align="center " />
      <el-table-column label="操作" width="200" align="center">
        <template #default="scope" v-if="$store.state.user.group != 1">
          <el-button @click="handleSetEmployee(scope.row)" text type="primary" class="p-1">
            <el-icon class="el-icon--left" :size="16">
              <Edit />
            </el-icon>部门员工
          </el-button>

          <el-button @click="handleEdit(scope.row)" text type="primary" class="p-1">
            <el-icon class="el-icon--left" :size="16">
              <Edit />
            </el-icon>修改
          </el-button>

          <el-popconfirm title="是否要删除该部门？" confirmButtonText="确认" cancelButtonText="取消"
            @confirm="handleDelete(scope.row.id)">
            <template #reference>
              <el-button text type="danger" class="p-1">
                <el-icon class="el-icon--left" :size="16">
                  <Delete />
                </el-icon>删除
              </el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="flex items-center justify-center mt-5">
      <el-pagination background layout="prev, pager ,next" :total="total" :current-page="currentPage"
        :page-size="pageSize" @current-change="getList" />
    </div>


    <!-- 新增/修改 -->
    <FormDrawer destroyOnClose ref="formDrawerRef" size="30%" :title="drawerTitle" @submit="selfHandleSubmit">
      <el-form :model="form" ref="formRef" :rules="rules" label-width="150px" :inline="false">
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="form.name" placeholder="部门名称"></el-input>
        </el-form-item>

        <!-- <el-form-item label="企业" prop="company_id">
          <el-select placeholder="请输入所属企业..." v-model="form.company" style="width: 100%">
            <el-option v-for="item in companyList" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item> -->
      </el-form>
    </FormDrawer>
  </el-card>

  <el-dialog v-model="dialogVisible" title="设置员工部门" width="80%" :before-close="handleClose">
    <div style="text-align: center">
        <el-transfer  v-model="selectEmployeeValue" :props="{
      key: 'id',
      label: 'username',
    }" :titles="titles" filterable :filter-method="filterMethod" filter-placeholder="State Abbreviations"
          :data="employeeList" />
        <el-button size="small" type="primary" @click="setEmployeeList">确定</el-button>
      </div>
  </el-dialog>
</template>
<script setup>
// vue 内部方法
import { ref, onMounted } from 'vue'

// 页面组件
import ListHeader from "~/components/ListHeader.vue"
import FormDrawer from "~/components/FormDrawer.vue"
import SearchForm from "~/components/SearchForm.vue"
import SearchItem from "~/components/SearchItem.vue"
import UploadFile from "~/components/UploadFile.vue"
import { Search } from '@element-plus/icons-vue'

// 公共方法
import { useInitTable, useInitForm } from "~/composables/useCommon"
import { showPrompt, toast } from "~/composables/util.js";

// api
import {
  getDepartmentList,
  postDepartment,
  putDepartment,
  deleteDepartment,
  getALLCompanyList,
  getEmployeeList,
  putEmployeeList,
} from "~/api/company/index"

// 初始化表格
const {
  searchForm,
  resetSearchForm,
  tableData,
  loading,
  currentPage,
  total,
  pageSize,
  getList,
  handleDelete,
} = useInitTable({
  searchForm: { search: "", id: "", name: "" },
  requestListAPI: getDepartmentList,
  delete: deleteDepartment,
  // pageSize: store.state.pageSize.MessageList,
  pageSize: 10,
  onGetListSuccess: (res) => {
    tableData.value = res.data.results
  },
})

// 初始化表单
const {
  formDrawerRef,
  formRef,
  form,
  rules,
  editId,
  drawerTitle,
  handleSubmit,
  resetForm,
  handleCreate,
  handleEdit,
} = useInitForm({
  getList,
  create: postDepartment,
  update: putDepartment,
  form: {
    name: "",
    company: '',
  },
  // onGetDataSuccess: (res) => {
  //   // 将接口返回的公司列表数据命名为companyAllList
  //   companyAllList.value = res.data.name;
  // },
  rules: {
    name: [
      {
        required: true,
        message: "部门名称不能为空",
        trigger: "blur",
      },
    ],
    company: [
      {
        required: true,
        message: "请选择公司",
        trigger: "blur",
      },
    ],
  }

});


const companyList = ref([])
const employeeList = ref([])
const selectEmployeeValue = ref([])
onMounted(() => {
  // 获取公司用户
  getALLCompanyList().then((res) => {
    companyList.value = res.data
  })

  // 获取公司员工
  getEmployeeList({}).then((res) => {
    employeeList.value = res.data.results
  })

})


const filterMethod = (query, item) => {
  return item.username.includes(query)
}

const selfHandleSubmit = () =>{
  form.company = companyList.value[0].id
  handleSubmit()
}

const titles = ref(['员工', '部门'])
// 设置员工
const dialogVisible = ref(false)
const department_id = ref('')
const handleSetEmployee = (row) => {
  dialogVisible.value = true
  department_id.value = row.id
  // 设置标题
  titles.value = ['员工 - ', '部门 - ' + row.name]

}

const setEmployeeList = () => {
  let data = {
    department_id:department_id.value,
    selectEmployeeValue:selectEmployeeValue.value,
  }
  putEmployeeList(data).then((res) => {
     if(res.code == 200){
      toast("修改成功");
      dialogVisible.value = false
      department_id.value = ''
     }else{
      toast("修改失败",'error');
     }
  })

}

</script>

<style scoped></style>